const { notify } = require("node-notifier");
const path = require("path");
const { NodeSSH } = require("node-ssh");
const { exec } = require("child_process");
const ssh = new NodeSSH();
const execPromise = (command) => {
    return new Promise((resolve, reject) => {
        exec(command, (err, stdout, stderr) => {
            if (err) {
                reject(err);
            } else {
                resolve({
                    stdout,
                    stderr,
                });
            }
        });
    });
};

async function deployProject() {
    try {
        const start = Date.now();
        await ssh.connect({
            host: "",
            port: 22,
            username: "root",
            password: "",
        });

        console.log("==========打包开始============");

        await Promise.all([
            execPromise(
                "cd C:\\data_yp\\project\\antique\\antique_admin && npm run build"
            ),
        ]);
        console.log('打包耗时', (Date.now() - start)/1000, 's');

        console.log("==========打包完成============");
        console.log("==========开始上传打包文件============");
        await Promise.all([
            ssh.putDirectory(
                "C:\\data_yp\\project\\antique\\antique_admin\\dist",
                "/java/dist/"
            ),
        ]);
        console.log("==========上传完成============");
        console.log("==========开始刷新nginx============");
        await ssh.execCommand("/usr/local/nginx/sbin/nginx -s reload");
        console.log("==========刷新nginx完成============");


        notify({
            title: "发布成功",
            message: "项目发布成功，上线大吉！！！！！",
            //  icon: path.join(__dirname, "11.jpg"),
            sound: true, // 播放提示音
            wait: false, // 用户点击通知时才消失
        });

        const end = Date.now();
        console.log("总耗时:", (end - start) / 1000, "s");
    } catch (err) {
        console.log("错误信息", err);
    } finally {
        ssh.dispose();
    }
}

deployProject();
